#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

#define THREAD_COUNT 20000
static pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
void *add_thread(void *arg)
{
    int *p = (int *)arg;
    // 上锁
    pthread_mutex_lock(&counter_mutex);
    *p = *p + 1;
    // 解锁
    pthread_mutex_unlock(&counter_mutex);
    return NULL;
}
int main(int argc, char const *argv[])
{
    pthread_t threads[THREAD_COUNT];
    int num;
    for (int i = 0; i < THREAD_COUNT; i++)
    {
        pthread_create(&threads[i], NULL, add_thread, &num);
    }
    for (int i = 0; i < THREAD_COUNT; i++)
    {
        pthread_join(threads[i], NULL);
    }
    printf("num = %d\n", num);
    // 销毁锁
    pthread_mutex_destroy(&counter_mutex);
    return 0;
}
